package me.ree.zkproduct.common.impl;

import lombok.Data;
import me.ree.zkproduct.common.ConnectionPool;
import org.springframework.beans.factory.FactoryBean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Data
public class ConnectionPoolFactoryBean implements FactoryBean<ConnectionPool> {

    private String connectionUrl;

    private String username;

    private String password;


    @Override
    public ConnectionPool getObject() throws Exception {
        SimpleConnectionPool pool = new SimpleConnectionPool();
        // 假设我们创建了10个连接并添加到连接池中
        for (int i = 0; i < 10; i++) {
            Connection connection = createConnection(connectionUrl, username, password);
            pool.addConnection(connection);
        }
        return pool;
    }

    private Connection createConnection(String url, String user, String password) throws SQLException {
        // 实现创建数据库连接的逻辑
        return DriverManager.getConnection(connectionUrl, username, password);
    }

    @Override
    public Class<ConnectionPool> getObjectType() {
        return ConnectionPool.class;
    }

    @Override
    public boolean isSingleton() {
        return true; // 连接池通常是一个单例
    }
}
